package com.hzdl.car.controller;

import com.github.pagehelper.PageInfo;
import com.hzdl.car.bean.News;
import com.hzdl.car.bean.User;
import com.hzdl.car.service.NewsService;
import com.hzdl.car.util.HzdlResultJson;
import com.hzdl.car.util.ResultObj;
import com.hzdl.car.vo.NewsVo;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@RequestMapping("news")
@RestController
public class NewsController {
    @Resource
    private NewsService newsService;
    @RequestMapping("findNews")
    public HzdlResultJson findNews(NewsVo newsVo){
        PageInfo<News> pageInfo=newsService.findNews(newsVo);
        return HzdlResultJson.ok(pageInfo.getTotal(),pageInfo.getList());
    }
    @RequestMapping("delNews")
    public ResultObj delNews(NewsVo newsVo){
        try {
            newsService.dekNews(newsVo);
            return ResultObj.DELETE_SUCCESS;

        }catch (Exception e){
            return  ResultObj.DELETE_ERROR;
        }
    }
    @RequestMapping("newsDelChk")
    public ResultObj newsDelChk(@RequestParam(value = "ids[]") Integer[] ids){
        try {
            newsService.newsDelChk(ids);
            return ResultObj.DELETE_SUCCESS;
        }catch (Exception e){
            return ResultObj.DELETE_ERROR;
        }
    }
    @RequestMapping("newsAdd")
    public ResultObj newsAdd(NewsVo newsVo, HttpSession session){
        try {
            Object o=session.getAttribute("user");
            if(o!=null){
                User user=(User)o;
                newsVo.setPublisherName(user.getRealName());
            }
            newsService.addNews(newsVo);
            return ResultObj.ADD_SUCCESS;
        }catch (Exception e){
            return ResultObj.ADD_ERROR;
        }
    }
    @RequestMapping("newsUpdate")
    public ResultObj newsUpdate(NewsVo newsVo){
        try {
            newsService.newsUpdate(newsVo);
            return ResultObj.UPDATE_SUCCESS;
        }catch (Exception e){
            return ResultObj.UPDATE_ERROR;
        }
    }
    @ResponseBody
    @RequestMapping("showNews")
    public HzdlResultJson showNews(){
        PageInfo pageInfo=newsService.showNews();
        return HzdlResultJson.ok(pageInfo.getTotal(), pageInfo.getList());
    }
}
